<template>
  <div class="storage-status">
    <el-card class="status-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><DataAnalysis /></el-icon>
          <span>存储状态</span>
          <el-button 
            type="text" 
            size="small" 
            @click="refreshStatus"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>
      </template>
      
      <div class="status-content">
        <!-- 当前策略状态 -->
        <div class="current-status">
          <div class="status-row">
            <span class="label">当前策略:</span>
            <el-tag :type="getStrategyTagType(currentStrategy?.type)" size="small">
              {{ getStrategyName(currentStrategy?.type) }}
            </el-tag>
          </div>
          
          <div class="status-row">
            <span class="label">连接状态:</span>
            <el-tag 
              :type="currentStrategy?.available ? 'success' : 'danger'" 
              size="small"
            >
              <el-icon style="margin-right: 4px;">
                <component :is="currentStrategy?.available ? 'CircleCheck' : 'CircleClose'" />
              </el-icon>
              {{ currentStrategy?.available ? '正常' : '异常' }}
            </el-tag>
          </div>
          
          <div class="status-row">
            <span class="label">最后检测:</span>
            <span class="timestamp">{{ formatTimestamp(currentStrategy?.timestamp) }}</span>
          </div>
        </div>
        
        <!-- 统计信息 -->
        <el-divider content-position="left">
          <span class="divider-text">统计信息</span>
        </el-divider>
        
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-value">{{ stats.totalFiles }}</div>
            <div class="stat-label">总文件数</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ formatFileSize(stats.totalSize) }}</div>
            <div class="stat-label">总大小</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.todayUploads }}</div>
            <div class="stat-label">今日上传</div>
          </div>
          
          <div class="stat-item">
            <div class="stat-value">{{ stats.successRate }}%</div>
            <div class="stat-label">成功率</div>
          </div>
        </div>
        
        <!-- 策略列表 -->
        <el-divider content-position="left">
          <span class="divider-text">策略状态</span>
        </el-divider>
        
        <div class="strategies-status">
          <div 
            v-for="(strategy, type) in allStrategies" 
            :key="type"
            class="strategy-status-item"
            :class="{ 'active': type === currentStrategy?.type }"
          >
            <el-icon class="strategy-icon" :class="`icon-${type}`">
              <component :is="getIconComponent(type)" />
            </el-icon>
            <span class="strategy-name">{{ getStrategyName(type) }}</span>
            <el-icon 
              class="status-icon" 
              :class="strategy.available ? 'status-success' : 'status-error'"
            >
              <component :is="strategy.available ? 'CircleCheck' : 'CircleClose'" />
            </el-icon>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DataAnalysis, 
  Refresh, 
  CircleCheck, 
  CircleClose,
  Folder, 
  Coin, 
  Cloudy 
} from '@element-plus/icons-vue'
import { StorageApi, StorageTypeNames } from '../utils/storageApi'

export default {
  name: 'StorageStatus',
  components: {
    DataAnalysis,
    Refresh,
    CircleCheck,
    CircleClose,
    Folder,
    Coin,
    Cloudy
  },
  setup() {
    const loading = ref(false)
    const currentStrategy = ref(null)
    const allStrategies = ref({})
    const stats = reactive({
      totalFiles: 0,
      totalSize: 0,
      todayUploads: 0,
      successRate: 95.8
    })
    
    let refreshTimer = null
    
    // 获取当前策略状态
    const loadCurrentStrategy = async () => {
      try {
        const response = await StorageApi.getCurrentStrategy()
        if (response.success) {
          currentStrategy.value = response.data
        }
      } catch (error) {
        console.error('获取当前策略失败:', error)
      }
    }
    
    // 获取所有策略状态
    const loadAllStrategies = async () => {
      try {
        const response = await StorageApi.getAllStrategies()
        if (response.success) {
          allStrategies.value = response.data
        }
      } catch (error) {
        console.error('获取策略列表失败:', error)
      }
    }
    
    // 获取统计信息（模拟数据）
    const loadStats = async () => {
      try {
        // 这里可以调用实际的统计API
        stats.totalFiles = Math.floor(Math.random() * 1000) + 500
        stats.totalSize = Math.floor(Math.random() * 1024 * 1024 * 1024 * 10) // 10GB内随机
        stats.todayUploads = Math.floor(Math.random() * 50) + 10
        stats.successRate = (95 + Math.random() * 4).toFixed(1)
      } catch (error) {
        console.error('获取统计信息失败:', error)
      }
    }
    
    // 刷新状态
    const refreshStatus = async () => {
      loading.value = true
      try {
        await Promise.all([
          loadCurrentStrategy(),
          loadAllStrategies(),
          loadStats()
        ])
      } finally {
        loading.value = false
      }
    }
    
    // 获取策略名称
    const getStrategyName = (type) => {
      return StorageTypeNames[type] || type
    }
    
    // 获取策略标签类型
    const getStrategyTagType = (type) => {
      const typeMap = {
        'local': 'success',
        'minio': 'warning',
        'oss': 'primary'
      }
      return typeMap[type] || 'info'
    }
    
    // 获取图标组件
    const getIconComponent = (type) => {
      const iconMap = {
        'local': 'Folder',
        'minio': 'Coin',
        'oss': 'Cloudy'
      }
      return iconMap[type] || 'Folder'
    }
    
    // 格式化时间戳
    const formatTimestamp = (timestamp) => {
      if (!timestamp) return '未知'
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN')
    }
    
    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    // 组件挂载
    onMounted(() => {
      refreshStatus()
      // 每30秒自动刷新一次状态
      refreshTimer = setInterval(refreshStatus, 30000)
    })
    
    // 组件卸载
    onUnmounted(() => {
      if (refreshTimer) {
        clearInterval(refreshTimer)
      }
    })
    
    return {
      loading,
      currentStrategy,
      allStrategies,
      stats,
      refreshStatus,
      getStrategyName,
      getStrategyTagType,
      getIconComponent,
      formatTimestamp,
      formatFileSize
    }
  }
}
</script>

<style scoped>
.storage-status {
  height: 100%;
}

.status-card {
  height: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  color: #409eff;
  font-size: 18px;
}

.card-header span {
  flex: 1;
  font-weight: 600;
}

.status-content {
  height: 100%;
  overflow-y: auto;
}

.current-status {
  margin-bottom: 16px;
}

.status-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.label {
  width: 80px;
  color: #606266;
  font-size: 14px;
}

.timestamp {
  font-size: 12px;
  color: #909399;
}

.divider-text {
  color: #909399;
  font-size: 12px;
  font-weight: 500;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

.stat-item {
  text-align: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #606266;
}

.strategies-status {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.strategy-status-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s;
}

.strategy-status-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.strategy-status-item.active {
  border-color: #409eff;
  background: #e6f7ff;
}

.strategy-icon {
  margin-right: 8px;
  font-size: 16px;
}

.strategy-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
}

.status-icon {
  font-size: 16px;
}

.status-success {
  color: #67c23a;
}

.status-error {
  color: #f56c6c;
}

/* 图标颜色 */
.icon-local {
  color: #67c23a;
}

.icon-minio {
  color: #c21f30;
}

.icon-oss {
  color: #ff6600;
}
</style> 